/**
 * @file WriteData.as
 *  本机数据读写
 * @author db0@qq.com
 * @version 1.0.1
 * @date 2014-02-25
 */
package 
{
	import flash.filesystem.StorageVolumeInfo;
	import flash.filesystem.StorageVolume;
	import flash.display.Loader;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.utils.ByteArray;
	import flash.filesystem.*;
	public class WriteData 
	{
		private static var sdcard_path:String = null;
		public static var overrideFile:Boolean = true;
		public static function get sdcard():String// = 
		{
			return File.applicationDirectory.nativePath +  "/data";
		}
		public function WriteData(filename:String="test.txt",data:String="testdata")
		{
			var bytes:ByteArray= new ByteArray();
			bytes.writeUTFBytes(data);
			write_bytes(filename,bytes,true);
			/*logs.adds(read_data(filename));*/
		}

		public static function get_txt_file(filename:String):File
		{
			/*var source:File = File.desktopDirectory.resolvePath("test.txt");*/
			if(filename.charAt(0)=="/")filename = filename.substr(1);
			var target:File = new File(sdcard+"/"+filename.replace(/\\/g,"/"));
			return target;
		}

		public static function get_photo_file(filename:String):File
		{
			if(filename.charAt(0)=="/")filename = filename.substr(1);
			filename = filename.replace(/^http:[\/]+/m,"").replace(/[\/]+/g,"/");
			var target:File = new File(sdcard+"/"+filename.replace(/\\/g,"/"));
			//logs.adds("get_photo_file:"+target.nativePath);
			return target;
		}

		public static function usrDir(UserId:String=null):File
		{
			if(UserId == null)UserId = "";
			var target:File = new File(sdcard+"/"+UserId);
			return target;
		}

		public static function write_bmpd(filename:String,bmpd:BitmapData):File
		{
			var bytes:ByteArray = PNGEncoder.encode(bmpd);
			return write_bytes(filename,bytes,false);
		}

		public static function displayObject_bitmapDate(obj:DisplayObject):BitmapData
		{
			var bmpd:BitmapData = new BitmapData(obj.width,obj.height,true,0x00000000);
			bmpd.draw(obj);
			return bmpd;
		}

		public static function read_bmpd(filename:String,loaded:Function):Loader
		{
			var bytes:ByteArray = read_bytes(filename,false);
			if(bytes)
				return SwfLoader.loadBytes(bytes,loaded);
			else
				return null;
		}

		/**
		 * 跟用户无关配置读写
		 */
		public static function read_txt(filename:String):String
		{
			var bytes:ByteArray = read_bytes(filename,true,true);
			if(bytes)
				return bytes.toString();
			return null;
		}
		public static function write_txt(filename:String,s:String):void
		{
			var bytes:ByteArray= new ByteArray();
			bytes.writeUTFBytes(s);
			write_bytes(filename,bytes,true,true);
		}
		public static function removeFile(filename:String):void
		{
			var target:File;
			target = new File(sdcard+"/"+filename.replace(/\\/g,"/"));
			if(target.exists)
			{
				target.deleteFile();
				logs.adds("removeFiles:",target.nativePath);
			}
		}


		public static function write_bytes(filename:String,data:ByteArray,istxt:Boolean=false,isRoot:Boolean=false):File
		{
			var target:File;
			if(isRoot){//跟用户无关
				target = new File(sdcard+"/"+filename.replace(/\\/g,"/"));
			}else{
				if(istxt)target = get_txt_file(filename);
				else target = get_photo_file(filename);
			}
			if(target.exists && !overrideFile)return null;
			var targetParent:File = target.parent;
			if(targetParent.exists){
				/*logs.adds("exists:",targetParent.nativePath);*/
			}else{
				/*logs.adds("not exists:",targetParent.nativePath);*/
				targetParent.createDirectory();
			}
			var fileStream:FileStream = new FileStream();
			try{
				fileStream.open(target, FileMode.WRITE);
				data.position = 0;
				fileStream.writeBytes(data);
				fileStream.truncate();
				fileStream.close();
				logs.adds("write_bytes:",target.nativePath);
			}catch(e:Error){
				logs.adds("WriteData.write_bytes",e);
			}
			/*source.moveTo(target, true);*/
			return target;
		}
		public static function removeFiles(dir:String=null,filter:String="^TopLogin"):void
		{
			var UserId:String = "";
			if(dir == null){
				/*logs.adds("usrDir:",usrDir(UserId).nativePath);*/
				if(usrDir(UserId).exists)dir = usrDir(UserId).nativePath;
				else return;
			}
			var  arr:Vector.<File> = getFilesInDir(dir,filter);
			for each(var file:File in arr)
			{
				file.deleteFile();
				logs.adds("removeFiles:",file.nativePath);
			}
		}
		public static function getFilesInDir(dir:String=null,type:String=".*"):Vector.<File>
		{
			var directory:File = File.applicationDirectory.resolvePath(dir);
			if(directory && directory.exists && directory.isDirectory)
			{
				var filelist:Array = directory.getDirectoryListing();//.sort(sortFun);
				var reg:RegExp = new RegExp(type, "i");
				var arr:Vector.<File>=null;
				for each (var file:File in filelist)
				{
					if (file.name.match(reg))
					{
						logs.adds(file.nativePath);
						if (arr == null) arr = new Vector.<File>();
						arr.push((file));
					}
				}
				return arr;
			}
			return null;
		}
		public static function getFilePathsInDir(dir:String=null,type:String=".*"):Array
		{
			var directory:File = File.applicationDirectory.resolvePath(dir);
			if(directory && directory.exists && directory.isDirectory)
			{
				var filelist:Array = directory.getDirectoryListing();//.sort(sortFun);
				var reg:RegExp = new RegExp(type, "i");
				var arr:Array =null;
				for each (var file:File in filelist)
				{
					if (file.name.match(reg))
					{
						logs.adds(file.nativePath);
						if (arr == null) arr = new Array;
						arr.push(file.url);
					}
				}
				return arr;
			}
			return null;
		}
		public static function getPassWord(UserId:String=null):String
		{
			/*logs.adds(UserId);*/
			if(UserId == null){
				UserId = "";
			}
			UserId = UserId.replace(/[\r\n ]/g,"");
			if(usrDir(UserId).exists){
				/*logs.adds(usrDir.nativePath);*/
				var arr:Vector.<File> = getFilesInDir(usrDir(UserId).nativePath,"^TopLogin");
				/*logs.adds(arr.length);*/
			}else{
				return null;
			}
			for each (var file:File in arr)
			{
				/*logs.adds(file.name);*/
				if(file.name.match("^TopLogin")){
					var password:String = Base64.decode(file.name.substr("TopLogin".length));
					/*logs.adds("pswd",password);*/
					return password;
				}
			}
			return null;
		}
		public static function get user_list():Array
		{
			var filelist:Vector.<File>= getFilesInDir(sdcard,".*");
			var ret_list:Array ;
			for each (var file:File in filelist){
				/*logs.adds("usr:",file.name);*/
				if(file.isDirectory && getPassWord(String(file.name))){
					if(ret_list == null)ret_list = new Array;
					ret_list.push(file.name);
				}
			}
			/*logs.adds("loged usr:",ret_list);*/
			return ret_list;
		}
		public static function read_bytes(filename:String,istxt:Boolean,isRoot:Boolean=false):ByteArray
		{
			var target:File;

			if(isRoot){
				target = new File(sdcard+"/"+filename.replace(/\\/g,"/"));
			}else{
				if(istxt)target = get_txt_file(filename);
				else target = get_photo_file(filename);
			}

			if(target.exists){
				var bytes:ByteArray = new ByteArray();
				var fileStream:FileStream = new FileStream();
				fileStream.open(target, FileMode.READ);
				fileStream.readBytes(bytes);
				fileStream.close();
				bytes.position = 0;
				logs.adds("read_bytes",target.nativePath);
				return bytes;
			}
			return null;
		}

		public static function read_config(path:String):String
		{
			var target:File = (File.applicationDirectory.resolvePath(path));
			if(target.exists){
				var bytes:ByteArray = new ByteArray();
				var fileStream:FileStream = new FileStream();
				fileStream.open(target, FileMode.READ);
				fileStream.readBytes(bytes);
				fileStream.close();
				bytes.position = 0;
				return bytes.toString();
			}
			return null;
		}
		public static function saveBitmap(path:String,obj:Bitmap):File
		{
			if(obj as Bitmap == null)
				return null;
			return WriteData.write_bmpd(path,obj.bitmapData);
		}

		public static function saveDisplayObject(path:String,obj:DisplayObject):File
		{
			return WriteData.write_bmpd(path,WriteData.displayObject_bitmapDate(obj));
		}
		public static function read_data(filename:String):String
		{
			var bytes:ByteArray = read_bytes(filename,true);
			if(bytes){
				return bytes.toString();
			}
			return null;
		}
	}
}

